/*
 *   Copyright (c) 2025 Huawei Device Co., Ltd.
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include "hilog/log.h"
#include "napi/native_api.h"

#include <thread>

#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0xFF00
#define LOG_TAG "250304163101077 sub thread"

#define CHECK_STATUS(status) ((status) == napi_status::napi_ok)


napi_threadsafe_function threadsafeFunction;
struct CallbackContext {
    napi_env env = nullptr;
    napi_ref callbackRef = nullptr;
};

/**
 * thread safe call js
 * @param env
 * @param js_callback
 * @param context
 * @param data
 */
static void ThreadSafeCallJs(napi_env env, napi_value js_callback, void *context, void *data) {
    CallbackContext *argcContext = reinterpret_cast<CallbackContext *>(data);
    if (argcContext != nullptr) {
        napi_get_reference_value(env, argcContext->callbackRef, &js_callback);
    } else {
        return;
    }

    // check is function,is not,release argcContext
    napi_valuetype type = napi_undefined;
    napi_typeof(env, js_callback, &type);
    if (type != napi_valuetype::napi_function) {
        napi_delete_reference(env, argcContext->callbackRef);
        delete argcContext;
        argcContext = nullptr;
        return;
    }

    napi_value result = nullptr;
    // execute js function,
    napi_call_function(env, nullptr, js_callback, 0, nullptr, &result);
    napi_delete_reference(env, argcContext->callbackRef);
    delete argcContext;
    argcContext = nullptr;
}

/**
 * execute sub thread
 * @param context current thread context
 */
void RunSubThread(CallbackContext *context) {
    if (context == nullptr) {
        return;
    }

    // Acquires a thread-safe function.
    napi_acquire_threadsafe_function(threadsafeFunction);
    OH_LOG_INFO(LOG_APP, "current thread is sub thread");

    // Calls a thread-safe function.
    OH_LOG_INFO(LOG_APP, "execute thread safe function  using type napi_tsfn_nonblocking");
    napi_call_threadsafe_function(threadsafeFunction, context, napi_tsfn_nonblocking);

    // Releases a thread-safe function.
    OH_LOG_INFO(LOG_APP, "release thread safe function");
    napi_release_threadsafe_function(threadsafeFunction, napi_tsfn_release);
}


/**
 * thread
 * @param env
 * @param info
 * args[0]: func
 * @return
 */
static napi_value ThreadSafeFunc(napi_env env, napi_callback_info info) {
    // args size,UI function
    size_t argc = 1;
    napi_value js_Callback;
    napi_get_cb_info(env, info, &argc, &js_Callback, nullptr, nullptr);

    napi_valuetype valueType;
    // check status is ok
    if (!CHECK_STATUS(napi_typeof(env, js_Callback, &valueType))) {
        OH_LOG_INFO(LOG_APP, "get type of js_Callback error");
        return nullptr;
    }
    // check argc is function
    if (napi_valuetype::napi_function != valueType) {
        return nullptr;
    }

    // create function name
    napi_value workName;
    if (!CHECK_STATUS(napi_create_string_utf8(env, "ThreadSafeName", NAPI_AUTO_LENGTH, &workName))) {
        OH_LOG_INFO(LOG_APP, "create workName error");
        return nullptr;
    }

    size_t max_queue_size = 0;
    size_t initial_thread_count = 1;
    napi_status status =
        napi_create_threadsafe_function(env, nullptr, nullptr, workName, max_queue_size, initial_thread_count, nullptr,
                                        nullptr, nullptr, ThreadSafeCallJs, &threadsafeFunction);
    if (!CHECK_STATUS(status)) {
        OH_LOG_INFO(LOG_APP, "create threadsafe function error");
        return nullptr;
    }

    auto context = new (std::nothrow) CallbackContext();
    context->env = env;
    if (CHECK_STATUS(!napi_create_reference(env, js_Callback, 1, &context->callbackRef))) {
        return nullptr;
    }

    std::thread t(RunSubThread, context);
    t.detach();
    return nullptr;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"threadSafeFunc", nullptr, ThreadSafeFunc, nullptr, nullptr, nullptr, napi_default, nullptr}};
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "subthreadlibrary",
    .nm_priv = ((void *)0),
    .reserved = {0},
};

extern "C" __attribute__((constructor)) void RegisterHarModule(void) { napi_module_register(&demoModule); }
